package com.qyhl.webtv.module_live.teletext.newlivelist;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.LiveRoomBean;
import com.qyhl.webtv.commonlib.entity.live.NewLiveListBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.GridDividerItemDecoration;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.qyhl.webtv.module_live.teletext.newlivelist.item.InteractionItemView;
import com.qyhl.webtv.module_live.teletext.newlivelist.item.OmnimediaItemView;
import com.qyhl.webtv.module_live.teletext.newlivelist.item.TagItemView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class NewLiveListFragment extends BaseFragment implements NewLiveListContract.NewLiveListView {
    @BindView(R2.id.back_btn)
    ImageView backBtn;
    @BindView(R2.id.title)
    TextView mTitle;
    @BindView(R2.id.newlive_recycleview)
    RecyclerView newliveRecycleview;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.title_layout)
    RelativeLayout titleLayout;

    private OtherDialog.Builder mDialog;

    private NewLiveListPresenter mPresenter;

    private String title;

    private boolean isBottom;

    private List<LiveRoomBean> traditionalList = new ArrayList<>();

    private List<LiveRoomBean> dataList = new ArrayList<>();

    private HeaderAndFooterWrapper headerAndFooterWrapper;

    private MultiItemTypeAdapter<LiveRoomBean> multiItemTypeAdapter;

    private RelativeLayout traditionalTitleLayout;

    private CommonAdapter<LiveRoomBean> commonAdapter;

    TextView traditionalMoreTv;


    public void setBottom(boolean bottom) {
        isBottom = bottom;
    }

    public void setTitle(String title) {
        this.title = title;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view;
        return view = inflater.inflate(R.layout.live_fragment_newlive_list, null);
    }

    @Override
    protected void create() {
        mPresenter = new NewLiveListPresenter(this);
        loadData();
    }

    @Override
    public void initImmersionBar() {
        if (!StringUtils.isEmpty(title)) {

            ImmersionBar.with(this)
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(true)
                    .statusBarColor(R.color.white)
                    .init();
        }
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    public static NewLiveListFragment newInstance(String title, boolean isBottom) {
        NewLiveListFragment fragment = new NewLiveListFragment();
        fragment.setTitle(title);
        fragment.setBottom(isBottom);
        return fragment;
    }

    public static NewLiveListFragment newInstance() {
        return new NewLiveListFragment();
    }


    /**
     * 加载数据
     */
    private void loadData() {
        //下拉刷新
        initView();
        setListeners();
    }


    @SuppressLint("InflateParams")
    private void initView() {
        if (isBottom) {
            backBtn.setVisibility(View.INVISIBLE);
        } else {
            backBtn.setVisibility(View.VISIBLE);
        }

        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        refreshLayout.setEnableLoadMore(false);

        loadMask.setStatus(LoadingLayout.Loading);
        if (StringUtils.isEmpty(title)) {
            titleLayout.setVisibility(View.GONE);
        } else {
            titleLayout.setVisibility(View.VISIBLE);
            mTitle.setText(title);
        }


        multiItemTypeAdapter = new MultiItemTypeAdapter<>(getContext(), dataList);
        multiItemTypeAdapter.addItemViewDelegate(new InteractionItemView(getContext()));
        multiItemTypeAdapter.addItemViewDelegate(new OmnimediaItemView(getContext()));
        multiItemTypeAdapter.addItemViewDelegate(new TagItemView(getContext()));

        headerAndFooterWrapper = new HeaderAndFooterWrapper(multiItemTypeAdapter);

        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.live_header_traditional_item, null);
        RecyclerView traditionalRecycleview = headerView.findViewById(R.id.traditional_live_recycleview);
        traditionalTitleLayout = headerView.findViewById(R.id.traditional_live_title);
        traditionalMoreTv = headerView.findViewById(R.id.traditional_live_more);


        traditionalRecycleview.setLayoutManager(new GridLayoutManager(getContext(), 2));
        traditionalRecycleview.addItemDecoration(new GridDividerItemDecoration(20, getResources().getColor(R.color.global_background)));
        traditionalRecycleview.setAdapter(commonAdapter = new CommonAdapter<LiveRoomBean>(getContext(), R.layout.live_item_newlive_traditional, traditionalList) {
            @Override
            protected void convert(ViewHolder viewHolder, LiveRoomBean liveRoomBean, int i) {
                viewHolder.setText(R.id.title, liveRoomBean.getTitle());
                if (!StringUtils.isEmpty(liveRoomBean.getHitcount())) {
                    viewHolder.setText(R.id.person_num, liveRoomBean.getHitcount() + "人参与");
                } else {
                    viewHolder.setText(R.id.person_num, "0人参与");
                }
                ImageView cover = viewHolder.getView(R.id.cover);
                Glide.with(getContext().getApplicationContext())
                        .load(liveRoomBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).transform(new GlideRoundTransform(4)))
                        .into(cover);
            }
        });

        headerAndFooterWrapper.addHeaderView(headerView);
        newliveRecycleview.setLayoutManager(new LinearLayoutManager(getContext()));
        newliveRecycleview.addItemDecoration(new RecycleViewDivider(
                getContext(), LinearLayoutManager.HORIZONTAL, 5, ContextCompat.getColor(getContext(), R.color.white)));
        newliveRecycleview.setAdapter(headerAndFooterWrapper);

        mPresenter.getDataList();

    }


    private void setListeners() {

        multiItemTypeAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                switch (dataList.get(i - 1).getLivetype()) {
                    case "interactive":
//                        Router.build("room_act").with("roomId", dataList.get(i - 1).getRoomId()).go(NewLiveListFragment.this);
                        break;
                    case "liveNews":
                        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TELETEXTDETAIL);
                        if (dataList.get(i - 1).getIsPsw() == 1) {
                            mDialog = new OtherDialog.Builder(getContext())
                                    .setContentView(R.layout.live_dialog_check_code)
                                    .setText(R.id.title, "请输入直播密码")
                                    .setDismissButton(R.id.negative_btn)
                                    .setCancelable(false)
                                    .setCanceledOnTouchOutside(false)
                                    .bundleInputWithoutDismissListener(R.id.code, R.id.positive_btn, new OtherDialog.InputListener() {
                                        @Override
                                        public void onClick(View view, String message) {
                                            if (StringUtils.isNotEmpty(message)) {
                                                showLoading();
                                                mPresenter.checkCode(dataList.get(i - 1).getRoomId() + "", message, dataList.get(i - 1));
                                                mDialog.dismiss();
                                            } else {
                                                showToast("请输入密码");
                                            }
                                        }
                                    });
                            mDialog.show();
                        } else {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                Bundle bundle = new Bundle();
                                bundle.putString("id", dataList.get(i - 1).getRoomId() + "");
                                //预告
                                if ("6".equals(dataList.get(i - 1).getStatus())) {
                                    RouterManager.router(ARouterPathConstant.TELE_TEXT_ACTIVITY, bundle);
                                } else {
                                    //视频
                                    if ("1".equals(dataList.get(i - 1).getType())) {
                                        RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
                                    } else {
                                        RouterManager.router(ARouterPathConstant.TELE_TEXT_ACTIVITY, bundle);
                                    }
                                }
                            } else {
                                showToast("此功能暂时不支持在当前手机系统版本上使用！");
                            }
                        }
                        break;
                    default:
                        break;
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });


        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                if ("1".equals(traditionalList.get(i).getType())) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", traditionalList.get(i).getRoomId() + "");
                    RouterManager.router(ARouterPathConstant.LIVE_VIDEO, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", traditionalList.get(i).getRoomId() + "");
                    RouterManager.router(ARouterPathConstant.LIVE_RADIO, bundle);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });


        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDataList();
            }
        });

        traditionalMoreTv.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("title", "传统直播");
            RouterManager.router(ARouterPathConstant.MIX_LIVE, bundle);
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> mPresenter.getDataList());

    }


    @OnClick({R2.id.back_btn})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.back_btn) {
            getActivity().finish();

        }
    }

    @Override
    public void setDataList(NewLiveListBean bean) {
        refreshLayout.finishRefresh();
        traditionalList.clear();
        dataList.clear();

        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        int limit = 4;

        if (bean.getProgramList() != null && bean.getProgramList().size() > 0) {
            traditionalTitleLayout.setVisibility(View.VISIBLE);
            if (bean.getProgramList().size() > limit) {
                traditionalMoreTv.setVisibility(View.VISIBLE);
                for (int i = 0; i < limit; i++) {
                    traditionalList.add(bean.getProgramList().get(i));
                }
            } else {
                traditionalMoreTv.setVisibility(View.GONE);
                traditionalList.addAll(bean.getProgramList());
            }
        } else {
            traditionalTitleLayout.setVisibility(View.GONE);
        }

        commonAdapter.notifyDataSetChanged();

        if (bean.getLiveNewsList() != null && bean.getLiveNewsList().size() > 0) {
            if (bean.getLiveNewsList().size() > limit) {
                dataList.add(new LiveRoomBean("tag", "1", true));
                for (int i = 0; i < limit; i++) {
                    dataList.add(bean.getLiveNewsList().get(i));
                }
            } else {
                dataList.add(new LiveRoomBean("tag", "1", false));
                dataList.addAll(bean.getLiveNewsList());
            }
        }

        if (bean.getLiveList() != null && bean.getLiveList().size() > 0) {
            if (bean.getLiveList().size() > limit) {
                dataList.add(new LiveRoomBean("tag", "2", true));
                for (int i = 0; i < limit; i++) {
                    dataList.add(bean.getLiveList().get(i));
                }
            } else {
                dataList.add(new LiveRoomBean("tag", "2", false));
                dataList.addAll(bean.getLiveList());
            }
        }

        headerAndFooterWrapper.notifyDataSetChanged();


    }

    @Override
    public void setError() {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText("获取失败！");
        loadMask.setReloadButtonText("点击重试~");
    }

    @Override
    public void checkResult(boolean isSuccess, LiveRoomBean bean) {
        dismissLoading();
        if (isSuccess) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", bean.getRoomId() + "");
                    //预告
                    if ("6".equals(bean.getStatus())) {
                        RouterManager.router(ARouterPathConstant.TELE_TEXT_ACTIVITY, bundle);
                    } else {
                        //视频
                        if ("1".equals(bean.getType())) {
                            RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
                        } else {
                            RouterManager.router(ARouterPathConstant.TELE_TEXT_ACTIVITY, bundle);
                        }
                    }
            } else {
                showToast("此功能暂时不支持在当前手机系统版本上使用！");
            }
        } else {
            showToast("密码错误");
        }
    }
}
